import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义选项接口
interface QuestionOption {
  key: string // 选项名称，如 'A', 'B', 'C'
  value: string // 选项内容
  attachment?: string // 附件
}

// 生成选项 key 的函数
const generateOptionKey = (index: number) => String.fromCharCode(65 + index)

// 生成初始选项的函数
const generateInitialOptions = (count: number = 2): QuestionOption[] => {
  return Array.from({ length: count }, (_, index) => ({
    key: generateOptionKey(index),
    value: ''
  }))
}

// 定义单选题表单数据接口
interface SingleChoiceForm {
  id?: number // 添加可选的 id 字段
  title: string
  options: QuestionOption[]
  answer: string
  analysis: string
  difficulty: number
  classId?: number
}

// 定义多选题表单数据接口
interface MultipleChoiceForm {
  id?: number // 添加可选的 id 字段
  title: string
  options: QuestionOption[]
  answer: string[] // 修改为字符串数组，存储多个答案
  analysis: string
  difficulty: number
  classId?: number
}

// 修改判断题表单数据接口
interface JudgeForm {
  id?: number // 添加可选的 id 字段
  title: string
  options: Array<{
    key: string
    value: string
    attachment?: string
  }>
  answer: string
  analysis: string
  difficulty: number
  classId?: number // 添加分类ID字段
}

// 修改简答题表单数据接口
interface ShortAnswerForm {
  id?: number // 添加可选的 id 字段
  title: string
  answer: string
  keywords: string[]
  analysis: string
  difficulty: number
  classId?: number // 添加分类ID字段
}

// 修改填空题表单数据接口
interface BlankForm {
  id?: number // 添加可选的 id 字段
  title: string
  blanks: string[] // 存储填空答案的数组
  analysis: string
  difficulty: number
  classId?: number
}

export const useQuestionStore = defineStore('question', () => {
  // 存储多个单选题的数据
  const singleChoiceForms = ref<SingleChoiceForm[]>([])
  // 存储多个多选题的数据
  const multipleChoiceForms = ref<MultipleChoiceForm[]>([])

  // 判断题表单数据
  const judgeForms = ref<JudgeForm[]>([])

  // 简答题表单数据
  const shortAnswerForms = ref<ShortAnswerForm[]>([])

  // 填空题表单数据
  const blankForms = ref<BlankForm[]>([])

  // 添加提交用的数据对象
  const submitData = ref({
    singleChoice: [] as SingleChoiceForm[],
    multipleChoice: [] as MultipleChoiceForm[],
    judge: [] as JudgeForm[],
    short: [] as ShortAnswerForm[],
    blank: [] as BlankForm[]
  })

  // 初始化一个新的单选题表单
  const initSingleChoiceForm = (): SingleChoiceForm => ({
    title: '',
    options: generateInitialOptions(),
    answer: '',
    analysis: '',
    difficulty: 1,
    classId: undefined
  })

  // 添加新的单选题
  const addSingleChoiceForm = () => {
    singleChoiceForms.value.push(initSingleChoiceForm())
    return singleChoiceForms.value.length - 1 // 返回新添加的表单索引
  }

  // 删除指定索引的单选题
  const removeSingleChoiceForm = (index: number) => {
    singleChoiceForms.value.splice(index, 1)
  }

  // 更新指定索引的单选题表单数据
  const updateSingleChoiceForm = (index: number, key: keyof SingleChoiceForm, value: any) => {
    singleChoiceForms.value[index] = {
      ...singleChoiceForms.value[index],
      [key]: value
    }
  }

  // 更新指定题目的选项内容
  const updateOption = (
    questionIndex: number,
    optionIndex: number,
    key: keyof Omit<QuestionOption, 'key'>,
    value: string
  ) => {
    const newOptions = [...singleChoiceForms.value[questionIndex].options]
    newOptions[optionIndex] = {
      ...newOptions[optionIndex],
      [key]: value
    }
    singleChoiceForms.value[questionIndex].options = newOptions
  }

  // 添加选项到指定题目
  const addOption = (questionIndex: number) => {
    const form = singleChoiceForms.value[questionIndex]
    if (form.options.length >= 26) return false
    const nextKey = generateOptionKey(form.options.length)
    form.options.push({
      key: nextKey,
      value: ''
    })
    return true
  }

  // 从指定题目中删除选项
  const removeOption = (questionIndex: number, optionIndex: number) => {
    const form = singleChoiceForms.value[questionIndex]
    if (form.options.length <= 2) return false
    form.options.splice(optionIndex, 1)
    // 重新排序选项的 key
    form.options = form.options.map((option, idx) => ({
      ...option,
      key: generateOptionKey(idx)
    }))
    return true
  }

  // 初始化一个新的多选题表单
  const initMultipleChoiceForm = (): MultipleChoiceForm => ({
    title: '',
    options: generateInitialOptions(),
    answer: [], // 初始化为空数组
    analysis: '',
    difficulty: 1,
    classId: undefined
  })

  // 添加新的多选题
  const addMultipleChoiceForm = () => {
    multipleChoiceForms.value.push(initMultipleChoiceForm())
    return multipleChoiceForms.value.length - 1
  }

  // 删除指定索引的多选题
  const removeMultipleChoiceForm = (index: number) => {
    multipleChoiceForms.value.splice(index, 1)
  }

  // 更新指定索引的多选题表单数据
  const updateMultipleChoiceForm = (index: number, key: keyof MultipleChoiceForm, value: any) => {
    multipleChoiceForms.value[index] = {
      ...multipleChoiceForms.value[index],
      [key]: value
    }
  }

  // 更新指定多选题的选项内容
  const updateMultipleOption = (
    questionIndex: number,
    optionIndex: number,
    key: keyof Omit<QuestionOption, 'key'>,
    value: string
  ) => {
    const newOptions = [...multipleChoiceForms.value[questionIndex].options]
    newOptions[optionIndex] = {
      ...newOptions[optionIndex],
      [key]: value
    }
    multipleChoiceForms.value[questionIndex].options = newOptions
  }

  // 添加选项到指定多选题
  const addMultipleOption = (questionIndex: number) => {
    const form = multipleChoiceForms.value[questionIndex]
    if (form.options.length >= 26) return false
    const nextKey = generateOptionKey(form.options.length)
    form.options.push({
      key: nextKey,
      value: ''
    })
    return true
  }

  // 从指定多选题中删除选项
  const removeMultipleOption = (questionIndex: number, optionIndex: number) => {
    const form = multipleChoiceForms.value[questionIndex]
    if (form.options.length <= 2) return false
    form.options.splice(optionIndex, 1)
    form.options = form.options.map((option, idx) => ({
      ...option,
      key: generateOptionKey(idx)
    }))
    return true
  }

  // 修改添加判断题的初始化方法
  const addJudgeForm = () => {
    judgeForms.value.push({
      title: '',
      options: [
        { key: 'A', value: '正确' },
        { key: 'B', value: '错误' }
      ],
      answer: '',
      analysis: '',
      difficulty: 1,
      classId: undefined // 初始化分类ID为undefined
    })
    return judgeForms.value.length - 1
  }

  // 删除判断题
  const removeJudgeForm = (index: number) => {
    judgeForms.value.splice(index, 1)
  }

  // 更新提交数据的方法
  const updateSubmitData = () => {
    submitData.value = {
      singleChoice: [...singleChoiceForms.value],
      multipleChoice: [...multipleChoiceForms.value],
      judge: [...judgeForms.value],
      short: [...shortAnswerForms.value],
      blank: [...blankForms.value]
    }
  }

  // 修复类型错误 - 更新 updateJudgeForm
  const updateJudgeForm = (
    index: number,
    field: keyof JudgeForm,
    value: JudgeForm[keyof JudgeForm]
  ) => {
    if (judgeForms.value[index]) {
      judgeForms.value[index] = {
        ...judgeForms.value[index],
        [field]: value
      }
    }
  }

  // 修改添加简答题的初始化方法
  const addShortAnswerForm = () => {
    shortAnswerForms.value.push({
      title: '',
      answer: '',
      keywords: [],
      analysis: '',
      difficulty: 1,
      classId: undefined // 初始化分类ID为undefined
    })
    return shortAnswerForms.value.length - 1
  }

  // 删除简答题
  const removeShortAnswerForm = (index: number) => {
    shortAnswerForms.value.splice(index, 1)
  }

  // 修复类型错误 - 更新 updateShortAnswerForm
  const updateShortAnswerForm = (
    index: number,
    field: keyof ShortAnswerForm,
    value: ShortAnswerForm[keyof ShortAnswerForm]
  ) => {
    if (shortAnswerForms.value[index]) {
      shortAnswerForms.value[index] = {
        ...shortAnswerForms.value[index],
        [field]: value
      }
    }
  }

  // 添加关键字
  const addKeyword = (questionIndex: number) => {
    if (shortAnswerForms.value[questionIndex].keywords.length < 6) {
      shortAnswerForms.value[questionIndex].keywords.push('')
    }
  }

  // 删除关键字
  const removeKeyword = (questionIndex: number, keywordIndex: number) => {
    shortAnswerForms.value[questionIndex].keywords.splice(keywordIndex, 1)
  }

  // 更新关键字
  const updateKeyword = (questionIndex: number, keywordIndex: number, value: string) => {
    shortAnswerForms.value[questionIndex].keywords[keywordIndex] = value
  }

  // 修改添加填空题的初始化方法
  const addBlankForm = () => {
    blankForms.value.push({
      title: '',
      blanks: [''], // 初始化时至少有一个空白答案
      analysis: '',
      difficulty: 1,
      classId: undefined
    })
    return blankForms.value.length - 1
  }

  // 删除填空题
  const removeBlankForm = (index: number) => {
    blankForms.value.splice(index, 1)
  }

  // 修改更新填空题的方法
  const updateBlankForm = (
    index: number,
    field: keyof BlankForm,
    value: BlankForm[keyof BlankForm]
  ) => {
    if (index >= 0 && index < blankForms.value.length) {
      blankForms.value[index] = {
        ...blankForms.value[index],
        [field]: value
      }
    }
  }

  // 添加填空答案
  const addBlank = (questionIndex: number) => {
    if (questionIndex >= 0 && questionIndex < blankForms.value.length) {
      if (blankForms.value[questionIndex].blanks.length < 6) {
        blankForms.value[questionIndex].blanks.push('')
      }
    }
  }

  // 删除填空答案
  const removeBlank = (questionIndex: number, blankIndex: number) => {
    if (questionIndex >= 0 && questionIndex < blankForms.value.length) {
      if (blankForms.value[questionIndex].blanks.length > 1) {
        blankForms.value[questionIndex].blanks.splice(blankIndex, 1)
      }
    }
  }

  // 更新填空答案
  const updateBlank = (questionIndex: number, blankIndex: number, value: string) => {
    if (questionIndex >= 0 && questionIndex < blankForms.value.length) {
      if (blankIndex >= 0 && blankIndex < blankForms.value[questionIndex].blanks.length) {
        blankForms.value[questionIndex].blanks[blankIndex] = value
      }
    }
  }

  // 添加重置数据的方法
  const resetAllData = () => {
    // 重置所有表单数据为空数组
    singleChoiceForms.value = []
    multipleChoiceForms.value = []
    judgeForms.value = []
    shortAnswerForms.value = []
    blankForms.value = []
    // 重置提交数据
    submitData.value = {
      singleChoice: [],
      multipleChoice: [],
      judge: [],
      short: [],
      blank: []
    }
  }

  // 修改提交数据的方法
  const submitQuestions = () => {
    // 更新提交数据
    updateSubmitData()

    // 构建提交的数据结构
    const submitJson = {
      // 单选题数据
      singleChoice: submitData.value.singleChoice.map((item) => ({
        id: item.id, // 添加 id 字段
        type: 'single',
        title: item.title,
        options: item.options,
        answer: item.answer,
        analysis: item.analysis,
        difficulty: item.difficulty,
        classId: item.classId
      })),

      // 多选题数据
      multipleChoice: submitData.value.multipleChoice.map((item) => ({
        id: item.id, // 添加 id 字段
        type: 'multiple',
        title: item.title,
        options: item.options,
        answer: item.answer,
        analysis: item.analysis,
        difficulty: item.difficulty,
        classId: item.classId
      })),

      // 判断题数据
      judge: submitData.value.judge.map((item) => ({
        id: item.id, // 添加 id 字段
        type: 'judge',
        title: item.title,
        options: item.options,
        answer: item.answer,
        analysis: item.analysis,
        difficulty: item.difficulty,
        classId: item.classId
      })),

      // 简答题数据
      short: submitData.value.short.map((item) => ({
        id: item.id, // 添加 id 字段
        type: 'short',
        title: item.title,
        answer: item.answer,
        keywords: item.keywords,
        analysis: item.analysis,
        difficulty: item.difficulty,
        classId: item.classId
      })),

      // 填空题数据
      blank: submitData.value.blank.map((item) => ({
        id: item.id, // 添加 id 字段
        type: 'blank',
        title: item.title,
        blanks: item.blanks,
        analysis: item.analysis,
        difficulty: item.difficulty,
        classId: item.classId
      }))
    }

    // 打印格式化的 JSON 数据
    console.log('提交的题目数据：')
    console.log(JSON.stringify(submitJson, null, 2))

    return submitJson
  }

  return {
    singleChoiceForms,
    multipleChoiceForms,
    judgeForms,
    shortAnswerForms,
    blankForms,
    addSingleChoiceForm,
    removeSingleChoiceForm,
    updateSingleChoiceForm,
    updateOption,
    addOption,
    removeOption,
    addMultipleChoiceForm,
    removeMultipleChoiceForm,
    updateMultipleChoiceForm,
    updateMultipleOption,
    addMultipleOption,
    removeMultipleOption,
    addJudgeForm,
    removeJudgeForm,
    updateJudgeForm,
    addShortAnswerForm,
    removeShortAnswerForm,
    updateShortAnswerForm,
    addKeyword,
    removeKeyword,
    updateKeyword,
    addBlankForm,
    removeBlankForm,
    updateBlankForm,
    addBlank,
    removeBlank,
    updateBlank,
    submitData,
    updateSubmitData,
    resetAllData,
    submitQuestions
  }
})
